import QtQuick 2.12
import QtQuick.Layouts 1.12
import QtQuick.Controls 2.12
import QtGraphicalEffects 1.12
import QtMultimedia 5.12

Rectangle {
    id: remoteControlPage
    color: "transparent"

    // 页面状态
    property bool manualMode: false // false: 参数预设自动运行, true: 远程手动控制
    // 监控区交互：聚焦的摄像头 (""/"front"/"rear")
    property string focusedCamera: ""
    
    // 添加键盘事件处理
    property bool keysEnabled: false
    
    // 组件初始化调试
    Component.onCompleted: {
        console.log("RemoteControlPage: Component completed successfully")
        console.log("RemoteControlPage: manualMode =", manualMode)
    }
    
    // 页面激活时调用的函数
    function onPageActivated() {
        console.log("RemoteControlPage: 页面已激活")
        // 向当前选中的下位机发送请求RTSP地址的JSON数据包
        requestRTSPAddresses()
    }
    
    // 请求RTSP地址的函数
    function requestRTSPAddresses() {
        console.log("RemoteControlPage: 请求RTSP地址")
        
        // 检查robotManager和currentRobot是否可用
        if (typeof robotManager !== 'undefined' && typeof mainWindow !== 'undefined' && mainWindow.currentRobot) {
            // 创建请求RTSP地址的JSON数据包
            var request = {
                "type": "request_rtsp_urls",
                "timestamp": Date.now()
            }
            
            console.log("RemoteControlPage: 发送RTSP地址请求到机器人 " + mainWindow.currentRobot)
            
            // 通过robotManager发送请求
            robotManager.sendControlCommand(mainWindow.currentRobot, request)
        } else {
            console.log("RemoteControlPage: 无法发送RTSP地址请求：robotManager或currentRobot不可用")
        }
    }
    
    // 更新RTSP地址的函数
    function updateRTSPUrls(frontUrl, rearUrl) {
        console.log("RemoteControlPage: 更新RTSP地址，前摄像头：" + frontUrl + "，后摄像头：" + rearUrl)
        
        // 更新前摄像头地址
        if (frontLoader.item && frontLoader.item.player) {
            console.log("RemoteControlPage: 停止前摄像头播放器")
            frontLoader.item.player.stop()
            console.log("RemoteControlPage: 设置前摄像头源为 " + frontUrl)
            frontLoader.item.player.source = frontUrl
            console.log("RemoteControlPage: 开始播放前摄像头")
            frontLoader.item.player.play()
        } else {
            console.warn("RemoteControlPage: 无法访问前摄像头播放器")
        }
        
        // 更新后摄像头地址
        if (rearLoader.item && rearLoader.item.player) {
            console.log("RemoteControlPage: 停止后摄像头播放器")
            rearLoader.item.player.stop()
            console.log("RemoteControlPage: 设置后摄像头源为 " + rearUrl)
            rearLoader.item.player.source = rearUrl
            console.log("RemoteControlPage: 开始播放后摄像头")
            rearLoader.item.player.play()
        } else {
            console.warn("RemoteControlPage: 无法访问后摄像头播放器")
        }
    }

    // 键盘事件处理
    Keys.onPressed: {
        if (!keysEnabled || !manualMode) return
        
        var direction = ""
        switch (event.key) {
            case Qt.Key_W:
                direction = "forward"
                event.accepted = true
                break
            case Qt.Key_S:
                direction = "backward"
                event.accepted = true
                break
            case Qt.Key_A:
                direction = "left"
                event.accepted = true
                break
            case Qt.Key_D:
                direction = "right"
                event.accepted = true
                break
            default:
                return
        }
        
        if (direction !== "") {
            sendControlCommand(direction)
        }
    }

    // 发送控制命令函数
    function sendControlCommand(direction) {
        console.log("发送控制命令: " + direction)
        
        // 创建JSON格式的控制命令
        var command = {
            "type": "control",
            "command": direction,
            "timestamp": Date.now()
        }
        
        // 生成原始Modbus指令
        if (typeof robotManager !== 'undefined' && robotManager.generateRawCommands) {
            var rawCommands = robotManager.generateRawCommands(direction)
            command.rawCommands = rawCommands
        }
        
        // 通过robotManager发送命令（需要在main.qml中定义）
        if (typeof robotManager !== 'undefined' && typeof mainWindow !== 'undefined' && mainWindow.currentRobot) {
            // 记录日志
            logControlCommand(command, mainWindow.currentRobot)
            
            // 发送命令到机器人
            robotManager.sendControlCommand(mainWindow.currentRobot, command)
        } else {
            console.log("无法发送控制命令：robotManager或currentRobot不可用")
        }
    }

    // 记录控制命令到日志文件
    function logControlCommand(command, robotSN) {
        // 这里只是示例，实际日志记录需要通过C++端实现
        console.log("记录控制命令到日志: Robot=" + robotSN + ", Command=" + JSON.stringify(command))
    }

    // 连接robotManager的信号，处理RTSP地址响应
    Connections {
        target: typeof robotManager !== 'undefined' ? robotManager : null
        
        onRobotDataReceived: function(sn, data) {
            // 检查是否是当前选中的机器人
            if (typeof mainWindow !== 'undefined' && sn === mainWindow.currentRobot) {
                // 处理RTSP地址响应
                if ((data.type === "rtsp_urls" || (data.type === "rtsp_urls_response" && data.status === "success"))) {
                    console.log("RemoteControlPage: 接收到RTSP地址响应", JSON.stringify(data))
                    
                    var frontUrl = ""
                    var rearUrl = ""
                    
                    // 处理旧格式的RTSP地址响应
                    if (data.type === "rtsp_urls") {
                        frontUrl = data.front_camera || "rtsp://192.168.126.182:8554/cam1"
                        rearUrl = data.rear_camera || "rtsp://192.168.126.182:8554/cam3"
                    }
                    // 处理新格式的RTSP地址响应
                    else if (data.type === "rtsp_urls_response" && data.status === "success") {
                        // 错误处理：检查必要字段
                        if (!data.rtsp_urls || !Array.isArray(data.rtsp_urls) || data.rtsp_urls.length < 1) {
                            console.warn("RemoteControlPage: RTSP响应数据格式不正确或URL数量不足")
                            return
                        }
                        
                        // 解析响应数据中的rtsp_urls数组
                        var rtspUrls = data.rtsp_urls
                        
                        // 使用第一个URL作为前摄像头的视频源
                        frontUrl = rtspUrls[0]
                        
                        // 如果有至少3个URL，使用第三个URL作为后摄像头的视频源
                        if (rtspUrls.length >= 3) {
                            rearUrl = rtspUrls[2]
                        }
                    }
                    
                    // 更新RTSP地址
                    updateRTSPUrls(frontUrl, rearUrl)
                }
            }
        }
    }

    ColumnLayout {
        anchors.fill: parent
        spacing: 16

        // 顶部模式选项卡
        RowLayout {
            spacing: 8
            Layout.alignment: Qt.AlignLeft
            Layout.preferredHeight: 90

            Button {
                id: autoModeBtn
                text: "参数预设自动运行"
                checkable: true
                checked: !manualMode
                onClicked: {
                    manualMode = false
                    keysEnabled = false
                }
                background: Rectangle {
                    radius: 6
                    color: autoModeBtn.checked ? "white" : "#eef2f5"
                    border.color: autoModeBtn.checked ? "#0A3D62" : "transparent"
                    border.width: autoModeBtn.checked ? 2 : 0
                }
                contentItem: Text {
                    text: autoModeBtn.text
                    color: autoModeBtn.checked ? "#0A3D62" : "#2c3e50"
                    font.pixelSize: 14
                    horizontalAlignment: Text.AlignHCenter
                    verticalAlignment: Text.AlignVCenter
                    elide: Text.ElideRight
                }
            }

            Button {
                id: manualModeBtn
                text: "远程手动控制"
                checkable: true
                checked: manualMode
                onClicked: {
                    manualMode = true
                    keysEnabled = true
                    // 设置焦点以接收键盘事件
                    remoteControlPage.forceActiveFocus()
                }
                background: Rectangle {
                    radius: 6
                    color: manualModeBtn.checked ? "white" : "#eef2f5"
                    border.color: manualModeBtn.checked ? "#0A3D62" : "transparent"
                    border.width: manualModeBtn.checked ? 2 : 0
                }
                contentItem: Text {
                    text: manualModeBtn.text
                    color: manualModeBtn.checked ? "#0A3D62" : "#2c3e50"
                    font.pixelSize: 14
                    horizontalAlignment: Text.AlignHCenter
                    verticalAlignment: Text.AlignVCenter
                    elide: Text.ElideRight
                }
            }
        }

        // 监控区（双摄像头）
        GridLayout {
            columns: 2
            columnSpacing: 16
            rowSpacing: 16
            Layout.fillWidth: true
            Layout.preferredHeight: 500

            // 左：前摄像头
            Loader {
                id: frontLoader
                sourceComponent: cameraPanel
                onLoaded: {
                    item.title = "前摄像头监控画面"
                    // 设置前摄像头RTSP流地址为初始空值，等待从机器人获取实际地址
                    item.videoSource = ""
                    if (item.clicked) item.clicked.connect(function(){ focusedCamera = (focusedCamera === "front" ? "" : "front") })
                }
                Layout.fillWidth: true
                Layout.preferredHeight: focusedCamera === "front" ? 500 : 390
                Layout.columnSpan: focusedCamera === "front" ? 2 : 1
                visible: focusedCamera !== "rear"
            }

            // 右：后摄像头
            Loader {
                id: rearLoader
                sourceComponent: cameraPanel
                onLoaded: {
                    item.title = "后摄像头监控画面"
                    // 设置后摄像头RTSP流地址为初始空值，等待从机器人获取实际地址
                    item.videoSource = ""
                    if (item.clicked) item.clicked.connect(function(){ focusedCamera = (focusedCamera === "rear" ? "" : "rear") })
                }
                Layout.fillWidth: true
                Layout.preferredHeight: focusedCamera === "rear" ? 500 : 390
                Layout.columnSpan: focusedCamera === "rear" ? 2 : 1
                visible: focusedCamera !== "front"
            }
        }

        // 控制区
        Rectangle {
            color: "white"
            radius: 8
            Layout.fillWidth: true
            Layout.preferredHeight: 320
            layer.enabled: true
            layer.effect: DropShadow {
                horizontalOffset: 0
                verticalOffset: 2
                radius: 8
                samples: 16
                color: "#20000000"
            }

            Loader {
                id: panelLoader
                anchors.fill: parent
                anchors.margins: 16
                sourceComponent: manualMode ? manualPanel : autoPanel
            }
        }
    }

    // 自动运行参数预设面板
    Component {
        id: autoPanel
        ColumnLayout {
            spacing: 16

            Label {
                text: "参数预设设置"
                font.pixelSize: 18
                font.bold: true
                color: "#2c3e50"
            }

            GridLayout {
                columns: 2
                columnSpacing: 16
                rowSpacing: 16
                Layout.fillWidth: true
                Layout.fillHeight: true

                // 左列
                ColumnLayout {
                    spacing: 16
                    Layout.fillWidth: true

                    // 预设作业模式
                    ColumnLayout {
                        spacing: 6
                        Label { text: "预设作业模式"; color: "#34495e"; font.pixelSize: 12 }
                        ComboBox {
                            model: ["标准平地作业", "坡地作业", "复杂地形作业", "精细作业模式", "快速作业模式"]
                            Layout.fillWidth: true
                        }
                    }

                    // 作业速度
                    ColumnLayout {
                        spacing: 6
                        Label { text: "作业速度"; color: "#34495e"; font.pixelSize: 12 }
                        Slider { id: speedSlider; from: 0; to: 3; stepSize: 0.1; value: 1.2; Layout.fillWidth: true }
                        RowLayout {
                            Layout.fillWidth: true
                            Label { text: "0 m/s"; color: "#7f8c8d"; font.pixelSize: 11 }
                            Item { Layout.fillWidth: true }
                            Label { text: "当前: " + speedSlider.value.toFixed(1) + " m/s"; color: "#7f8c8d"; font.pixelSize: 11 }
                            Item { Layout.fillWidth: true }
                            Label { text: "3 m/s"; color: "#7f8c8d"; font.pixelSize: 11 }
                        }
                    }

                    // 作业深度
                    ColumnLayout {
                        spacing: 6
                        Label { text: "作业深度"; color: "#34495e"; font.pixelSize: 12 }
                        Slider { id: depthSlider; from: 0; to: 50; stepSize: 1; value: 25; Layout.fillWidth: true }
                        RowLayout {
                            Layout.fillWidth: true
                            Label { text: "0 cm"; color: "#7f8c8d"; font.pixelSize: 11 }
                            Item { Layout.fillWidth: true }
                            Label { text: "当前: " + depthSlider.value.toFixed(0) + " cm"; color: "#7f8c8d"; font.pixelSize: 11 }
                            Item { Layout.fillWidth: true }
                            Label { text: "50 cm"; color: "#7f8c8d"; font.pixelSize: 11 }
                        }
                    }
                }

                // 右列
                ColumnLayout {
                    spacing: 16
                    Layout.fillWidth: true

                    // 路径规划
                    ColumnLayout {
                        spacing: 6
                        Label { text: "路径规划"; color: "#34495e"; font.pixelSize: 12 }
                        GridLayout {
                            id: routesGrid
                            columns: 4
                            columnSpacing: 12
                            rowSpacing: 0
                            Layout.fillWidth: true

                            // 单选索引，-1 表示未选
                            property int selectedIndex: -1
                            function applySelection() {
                                if (btn1.item) btn1.item.color = (selectedIndex === 0 ? "#60A3BC" : "transparent")
                                if (btn2.item) btn2.item.color = (selectedIndex === 1 ? "#60A3BC" : "transparent")
                                if (btn3.item) btn3.item.color = (selectedIndex === 2 ? "#60A3BC" : "transparent")
                                if (btn4.item) btn4.item.color = (selectedIndex === 3 ? "#60A3BC" : "transparent")
                            }

                            Loader {
                                id: btn1
                                sourceComponent: routeButton
                                onLoaded: {
                                    item.text = "直线模式"
                                    item.color = routesGrid.selectedIndex === 0 ? "#60A3BC" : "transparent"
                                    item.clicked.connect(function(){ routesGrid.selectedIndex = 0; routesGrid.applySelection() })
                                }
                                Layout.fillWidth: true
                                Layout.preferredHeight: 44
                            }
                            Loader {
                                id: btn2
                                sourceComponent: routeButton
                                onLoaded: {
                                    item.text = "往返模式"
                                    item.color = routesGrid.selectedIndex === 1 ? "#60A3BC" : "transparent"
                                    item.clicked.connect(function(){ routesGrid.selectedIndex = 1; routesGrid.applySelection() })
                                }
                                Layout.fillWidth: true
                                Layout.preferredHeight: 44
                            }
                            Loader {
                                id: btn3
                                sourceComponent: routeButton
                                onLoaded: {
                                    item.text = "螺旋模式"
                                    item.color = routesGrid.selectedIndex === 2 ? "#60A3BC" : "transparent"
                                    item.clicked.connect(function(){ routesGrid.selectedIndex = 2; routesGrid.applySelection() })
                                }
                                Layout.fillWidth: true
                                Layout.preferredHeight: 44
                            }
                            Loader {
                                id: btn4
                                sourceComponent: routeButton
                                onLoaded: {
                                    item.text = "自定义路径"
                                    item.color = routesGrid.selectedIndex === 3 ? "#60A3BC" : "transparent"
                                    item.clicked.connect(function(){ routesGrid.selectedIndex = 3; routesGrid.applySelection() })
                                }
                                Layout.fillWidth: true
                                Layout.preferredHeight: 44
                            }
                        }
                    }

                    // 作业时间设置
                    ColumnLayout {
                        spacing: 6
                        Label { text: "作业时间设置"; color: "#34495e"; font.pixelSize: 12 }
                        GridLayout {
                            columns: 2
                            columnSpacing: 8
                            rowSpacing: 8
                            Layout.fillWidth: true
                            ColumnLayout {
                                Label { text: "开始时间"; color: "#7f8c8d"; font.pixelSize: 11 }
                                TextField { placeholderText: "yyyy/mm/dd --:--"; Layout.fillWidth: true }
                            }
                            ColumnLayout {
                                Label { text: "结束时间"; color: "#7f8c8d"; font.pixelSize: 11 }
                                TextField { placeholderText: "yyyy/mm/dd --:--"; Layout.fillWidth: true }
                            }
                        }
                    }

                    // 操作按钮
                    RowLayout {
                        Layout.fillWidth: true
                        spacing: 8
                        Button {
                            text: "启动自动作业"
                            Layout.fillWidth: true
                            background: Rectangle { color: "#2ECC71"; radius: 6 }
                            contentItem: Text { text: "启动自动作业"; color: "white"; horizontalAlignment: Text.AlignHCenter; verticalAlignment: Text.AlignVCenter }
                            Layout.preferredHeight: 44
                        }
                        ColumnLayout {
                            spacing: 8
                            Layout.fillWidth: true
                            Button {
                                text: "保存预设"
                                Layout.fillWidth: true
                                background: Rectangle { color: "#e0e0e0"; radius: 6 }
                                contentItem: Text { text: "保存预设"; color: "#333"; horizontalAlignment: Text.AlignHCenter; verticalAlignment: Text.AlignVCenter }
                                Layout.preferredHeight: 30
                            }
                            Button {
                                text: "重置"
                                Layout.fillWidth: true
                                background: Rectangle { color: "#e0e0e0"; radius: 6 }
                                contentItem: Text { text: "重置"; color: "#333"; horizontalAlignment: Text.AlignHCenter; verticalAlignment: Text.AlignVCenter }
                                Layout.preferredHeight: 30
                            }
                        }
                    }
                }
            }
        }
    }

    // 手动控制面板
    Component {
        id: manualPanel
        ColumnLayout {
            spacing: 16
            Label {
                text: "手动控制"
                font.pixelSize: 18
                font.bold: true
                color: "#2c3e50"
            }

            // 已移除方向控制与方向辅助控制

            // 速度与功能控制
            ColumnLayout {
                spacing: 16

                // 行驶速度
                ColumnLayout {
                    spacing: 6
                    Label { text: "行驶速度"; color: "#34495e"; font.pixelSize: 12 }
                    Slider { id: driveSpeed; from: 0; to: 3; stepSize: 0.1; value: 0; Layout.fillWidth: true }
                    RowLayout {
                        Layout.fillWidth: true
                        Label { text: "停止"; color: "#7f8c8d"; font.pixelSize: 11 }
                        Item { Layout.fillWidth: true }
                        Label { text: "当前: " + driveSpeed.value.toFixed(1) + " m/s"; color: "#7f8c8d"; font.pixelSize: 11 }
                        Item { Layout.fillWidth: true }
                        Label { text: "最快"; color: "#7f8c8d"; font.pixelSize: 11 }
                    }
                }

                // 功能控制按钮
                GridLayout {
                    id: controlGrid
                    columns: 4
                    columnSpacing: 12
                    rowSpacing: 12
                    Layout.fillWidth: true
                    
                    // 选中索引，默认选中第一个按钮（启动作业装置）
                    property int selectedIndex: 0
                    
                    function applySelection() {
                        if (controlBtn1.item) {
                            controlBtn1.item.colorHex = (selectedIndex === 0 ? "#60A3BC" : "#e0e0e0")
                            controlBtn1.item.textColor = (selectedIndex === 0 ? "white" : "#333")
                        }
                        if (controlBtn2.item) {
                            controlBtn2.item.colorHex = (selectedIndex === 1 ? "#60A3BC" : "#e0e0e0")
                            controlBtn2.item.textColor = (selectedIndex === 1 ? "white" : "#333")
                        }
                        if (controlBtn3.item) {
                            controlBtn3.item.colorHex = (selectedIndex === 2 ? "#60A3BC" : "#e0e0e0")
                            controlBtn3.item.textColor = (selectedIndex === 2 ? "white" : "#333")
                        }
                        if (controlBtn4.item) {
                            controlBtn4.item.colorHex = (selectedIndex === 3 ? "#60A3BC" : "#e0e0e0")
                            controlBtn4.item.textColor = (selectedIndex === 3 ? "white" : "#333")
                        }
                    }
                    
                    Loader { 
                        id: controlBtn1
                        sourceComponent: controlButton
                        onLoaded: {
                            item.text = "启动作业装置"
                            item.colorHex = "#60A3BC"
                            item.textColor = "white"
                            item.clicked.connect(function(){
                                controlGrid.selectedIndex = 0
                                controlGrid.applySelection()
                            })
                        }
                    }
                    Loader { 
                        id: controlBtn2
                        sourceComponent: controlButton
                        onLoaded: {
                            item.text = "停止作业装置"
                            item.colorHex = "#e0e0e0"
                            item.textColor = "#333"
                            item.clicked.connect(function(){
                                controlGrid.selectedIndex = 1
                                controlGrid.applySelection()
                            })
                        }
                    }
                    Loader { 
                        id: controlBtn3
                        sourceComponent: controlButton
                        onLoaded: {
                            item.text = "拍照取证"
                            item.colorHex = "#e0e0e0"
                            item.textColor = "#333"
                            item.clicked.connect(function(){
                                controlGrid.selectedIndex = 2
                                controlGrid.applySelection()
                            })
                        }
                    }
                    Loader { 
                        id: controlBtn4
                        sourceComponent: controlButton
                        onLoaded: {
                            item.text = "语音指令"
                            item.colorHex = "#e0e0e0"
                            item.textColor = "#333"
                            item.clicked.connect(function(){
                                controlGrid.selectedIndex = 3
                                controlGrid.applySelection()
                            })
                        }
                    }
                }

                // 紧急停止
                Button {
                    text: "紧急停止"
                    Layout.fillWidth: true
                    background: Rectangle { color: "#E74C3C"; radius: 6 }
                    contentItem: Text { text: "⚠ 紧急停止"; color: "white"; horizontalAlignment: Text.AlignHCenter; verticalAlignment: Text.AlignVCenter; font.pixelSize: 16 }
                    Layout.preferredHeight: 48
                }
            }
        }
    }

    // 相机面板组件 - 精简优化版
    Component {
        id: cameraPanel
        Rectangle {
            id: cameraCard
            property string title: ""
            property url videoSource: ""
            signal clicked()
            color: "white"
            radius: 8
            Layout.fillWidth: true
            Layout.preferredHeight: 260

            layer.enabled: true
            layer.effect: DropShadow { radius: 8; samples: 16; color: "#20000000" }

            ColumnLayout {
                anchors.fill: parent
                spacing: 8
                Label { 
                    text: title
                    color: "#2c3e50"
                    font.bold: true
                    Layout.leftMargin: 12
                    Layout.topMargin: 12
                }
                
                Rectangle {
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    Layout.minimumHeight: 330
                    color: "#222"
                    radius: 8
                    anchors.margins: 8
                    clip: true
                    
                    // 视频播放器组件 - 精简优化版
                    MediaPlayer {
                        id: player
                        source: videoSource
                        autoPlay: true
                        loops: MediaPlayer.Infinite
                        
                        // 简化设置以减少延迟并启用硬件加速
                        property var options: QtObject {
                            property int bufferSize: 0  // 最小缓冲
                            property bool lowLatency: true
                            property string rtspTransport: "tcp"  // 使用TCP传输
                        }
                        
                        // 错误处理
                        onError: {
                            console.log("视频播放错误 [" + title + "]: " + errorString + " (" + source + ")")
                            // 尝试重新连接
                            reconnectTimer.restart()
                        }
                        
                        // 连接状态处理
                        onStatusChanged: {
                            if (status === MediaPlayer.Loaded) {
                                console.log("视频流已加载 [" + title + "]: " + source)
                                reconnectAttempts = 0
                                // 如果已经加载完成，检查播放状态
                                if (player.playbackState === MediaPlayer.PlayingState) {
                                    cameraCard.shouldShowIndicator = false
                                }
                            } else if (status === MediaPlayer.Buffering) {
                                console.log("视频流缓冲中 [" + title + "]: " + source)
                                cameraCard.shouldShowIndicator = true
                            } else if (status === MediaPlayer.Stalled) {
                                console.log("视频流卡顿 [" + title + "]: " + source)
                                // 尝试重新连接
                                cameraCard.shouldShowIndicator = true
                                reconnectTimer.restart()
                            } else if (status === MediaPlayer.EndOfMedia) {
                                console.log("视频流结束，重新播放 [" + title + "]: " + source)
                                cameraCard.shouldShowIndicator = true
                                player.play()
                            } else if (status === MediaPlayer.Invalid) {
                                console.log("视频流无效 [" + title + "]: " + source)
                                // 尝试重新连接
                                cameraCard.shouldShowIndicator = true
                                reconnectTimer.restart()
                            }
                        }
                        
                        // 播放状态处理
                        onPlaybackStateChanged: {
                            if (playbackState === MediaPlayer.PlayingState) {
                                console.log("视频流开始播放 [" + title + "]: " + source)
                                // 确保隐藏加载指示器
                                cameraCard.shouldShowIndicator = false
                            } else if (playbackState === MediaPlayer.PausedState) {
                                console.log("视频流暂停播放 [" + title + "]: " + source)
                            } else if (playbackState === MediaPlayer.StoppedState) {
                                console.log("视频流停止播放 [" + title + "]: " + source)
                            }
                        }
                    }
                    
                    // 重新连接尝试计数
                    property int reconnectAttempts: 0
                    property int maxReconnectAttempts: 5
                    
                    // 控制加载指示器显示的属性
                    property bool shouldShowIndicator: true
                    
                    // 重新连接定时器
                    Timer {
                        id: reconnectTimer
                        interval: 3000  // 3秒后重试
                        repeat: false
                        onTriggered: {
                            if (cameraCard.reconnectAttempts < cameraCard.maxReconnectAttempts) {
                                console.log("尝试重新连接 [" + title + "] (尝试 " + (cameraCard.reconnectAttempts + 1) + "/" + cameraCard.maxReconnectAttempts + ")")
                                cameraCard.reconnectAttempts++
                                cameraCard.shouldShowIndicator = true
                                player.stop()
                                player.play()
                            } else {
                                console.log("达到最大重新连接尝试次数 [" + title + "]")
                            }
                        }
                    }
                    
                    VideoOutput {
                        anchors.fill: parent
                        source: player
                        fillMode: VideoOutput.PreserveAspectFit
                        
                        // 优化渲染性能
                        smooth: false
                        antialiasing: false
                    }
                    
                    MouseArea { 
                        anchors.fill: parent
                        onClicked: cameraCard.clicked()
                        
                        // 添加重新加载功能
                        onDoubleClicked: {
                            console.log("重新加载视频流 [" + title + "]: " + player.source)
                            cameraCard.reconnectAttempts = 0
                            player.stop()
                            player.play()
                        }
                    }
                }
            }
        }
    }

    // 路径按钮组件
    Component {
        id: routeButton
        Rectangle {
            property alias text: label.text
            signal clicked()
            color: "transparent"
            border.color: "#e0e0e0"
            radius: 6
            Layout.fillWidth: true
            Layout.preferredHeight: 44
            MouseArea { anchors.fill: parent; onClicked: parent.clicked() }
            RowLayout { anchors.fill: parent; anchors.margins: 10; Label { id: label; color: "#555"; font.pixelSize: 12 } }
        }
    }

    // 功能控制按钮组件
    Component {
        id: controlButton
        Button {
            property string colorHex: "#e0e0e0"
            property string textColor: "#333"
            text: "按钮"
            background: Rectangle { color: colorHex; radius: 6 }
            contentItem: Text { text: parent.text; color: textColor; horizontalAlignment: Text.AlignHCenter; verticalAlignment: Text.AlignVCenter }
            Layout.fillWidth: true
            Layout.preferredHeight: 44
        }
    }
}